package cn.share.life.module.images.utils;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.io.File;
import java.util.List;

import static org.opencv.photo.Photo.INPAINT_TELEA;
import static org.opencv.photo.Photo.inpaint;

public class WatermarkRemoval {
    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    private static String IMAGE_PATH = "F:\\image\\0706";
    // 替换为你的水印图片路径
    private static String WATERMARK_IMAGE_PATH = "C:/Users/Administrator/Downloads/2/001.png";


    public static void main(String[] args) {
//        List<File> imageFileList = ImageFileUtils.getImageFileList(IMAGE_PATH);

        String inputImagePath = "F:/image/0706/bijini/1hc5axl.jpg"; // 替换为你的输入图片路径
        String outputImagePath = "C:/Users/Administrator/Downloads/2/2222.jpg"; // 替换为你的输出图片路径

        watermark(inputImagePath, outputImagePath);
    }

    public static void watermark(String inputImagePath, String outputImagePath){
        // 加载原始图像和水印图像

        Mat src = Imgcodecs.imread(inputImagePath);
        Mat watermark = Imgcodecs.imread(WATERMARK_IMAGE_PATH, Imgcodecs.IMREAD_GRAYSCALE);

        // 将原始图像转换为灰度图像
        Mat srcGray = new Mat();
        Imgproc.cvtColor(src, srcGray, Imgproc.COLOR_BGR2GRAY);

        // 使用模板匹配找到水印的位置
        Mat result = new Mat();
        Imgproc.matchTemplate(srcGray, watermark, result, Imgproc.TM_CCOEFF_NORMED);
        Core.MinMaxLocResult mmr = Core.minMaxLoc(result);

        // 获取水印的位置和大小
        int w = watermark.cols();
        int h = watermark.rows();
        Point matchLoc = mmr.maxLoc;

        // 创建一个掩码，用于标记水印区域
        Mat mask = new Mat(src.size(), CvType.CV_8UC1, new Scalar(0));
        Imgproc.rectangle(mask, matchLoc, new Point(matchLoc.x + w, matchLoc.y + h), new Scalar(255), -1);

        // 使用图像修复技术去除水印
        Mat blended = new Mat(src.size(), src.type());
        inpaint(src, mask, blended, 3, INPAINT_TELEA);

        // 保存去除水印后的图像
        Imgcodecs.imwrite(outputImagePath, blended);

        System.out.println("Watermark removed and saved to " + outputImagePath);
    }
}
